package com.laxia.codegenerator;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author weishuai
 */
public class FileGenerator {

    private static String rootPath = System.getProperty("user.dir");

    private static String serviceContent;
    private static String serviceImplContent;

    static {
        try {
            File file = new File(rootPath + "/src/test/java/com/laxia/codegenerator/dao.tmp");
            serviceContent = FileUtils.readFileToString(file, "utf-8");
            file = new File(rootPath + "/src/test/java/com/laxia/codegenerator/daoImpl.tmp");
            serviceImplContent = FileUtils.readFileToString(file, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void generateServiceFile(String schema, String tableName) {
        String currentContent = serviceContent.replace("#{tableName}", tableName).replace("#{schema}", schema);
        createFile(rootPath + "/gen/src/main/java/com/laxia/dao/" + tableName + "DAO.java", currentContent);
    }

    public static void generateImplServiceFile(String schema, String tableName) {
        String currentContent = serviceImplContent.replace("#{tableName}", tableName).replace("#{schema}", schema);
        createFile(rootPath + "/gen/src/main/java/com/laxia/dao/impl/" + tableName + "DAOImpl.java", currentContent);
    }

    private static void createFile(String path, String content) {
        try {
            File file = new File(path);
            if (!file.exists()) {
//                file.delete();
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    boolean mkdirs = parentFile.mkdirs();
                    System.out.println("dir created: " + mkdirs);
                }
                boolean newFile = file.createNewFile();
                System.out.println("file created: " + newFile + "," + path);
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write(content);
                fileWriter.flush();
                fileWriter.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
